# coding=utf-8

from flask import Flask, request
# from flask import request
from flask_cors import CORS
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
import json
import sys
import random
import time
import pymysql
import hashlib
import base64
import uuid

appfile = Flask(__name__)

# # r'/*' 是通配符，让本服务器所有的URL 都允许跨域请求
CORS(appfile, resources=r'/*')

# 短信
appid = 1400071450
appkey = "74697a8cccd198c936ba8079132b052d"
template_id = 96423
validTime = 1

# 数据库
server_host = '47.254.20.62'
user = 'root'
passwd = '65ut'
db = 'hghq_data'

# 图片路径
IMAGE_PATH = 'image/'


@appfile.route('/')
def hello_world():
    return 'hello_world'


@appfile.route('/hello')
def hello_user():
    data = {'msg': 'Hello'}
    return json.dumps(data)


# 保存提交的数据
@appfile.route('/save', methods=['POST', 'GET'])
def save():
    # 0:登记成功  1:用户已存在   2:验证码不正确
    privateCode = 0

    name = request.values.get('name', type=str, default=None)
    id_card = request.values.get("id_card", type=str, default=None)
    tel = request.values.get("tel", type=str, default=None)
    code = request.values.get("code", type=str, default=None)
    referrer = request.values.get("referrer", type=str, default=None)
    pwd = request.values.get("pwd", type=str, default=None)
    p1 = request.values.get("p1", type=str, default=None)
    p2 = request.values.get("p2", type=str, default=None)

    files = '%s;%s' % (p1, p2)

    conn = pymysql.Connect(host=server_host, port=3306,
                           user=user, passwd=passwd, db=db, charset='utf8')
    cursor = conn.cursor()

    selectSql = "SELECT id FROM tb_temp_code WHERE tel='%s' AND code='%s'" % (
        tel, code)
    cursor.execute(selectSql)

    if cursor.rowcount == 0:
        privateCode = 2
    else:
        selectSql = "SELECT id FROM tb_user WHERE id_card='%s'" % (id_card)
        cursor.execute(selectSql)

        # 该用户原来是否登记过
        if cursor.rowcount > 0:
            privateCode = 1
        else:
            insertSql = "INSERT INTO `hghq_data`.`tb_user` (\
                        `name`,\
                        `tel`,\
                        `id_card`,\
                        `referrer`,\
                        `pwd`,\
                        `files`,\
                        `add_time`,\
                        `is_del`\
                        ) \
                        VALUES\
                        (\
                            '%s',\
                            '%s',\
                            '%s',\
                            '%s',\
                            '%s',\
                            '%s',\
                            %d,\
                            0\
                        )" % \
                        (
                            name,
                            tel,
                            id_card,
                            referrer,
                            pwd,
                            files,
                            int(getNowTime())
                        )

            cursor.execute(insertSql)
            conn.commit()

    cursor.close()
    conn.close()

    return json.dumps({
        'code': privateCode
    })

# 保存图片
@appfile.route('/uploadImg', methods=['POST'])
def uploadImg():
    # 0:上传成功
    privateCode = 0

    p = request.values.get("p", type=str, default=None)
    id = request.values.get("id", type=str, default=None)

    fileName = str(uuid.uuid1()) + '.jpg'

    print(p)
    print(id)

    base64ToPicAndSave(p, fileName)

    return json.dumps({
        'code': privateCode,
        'msg': {
            'file': fileName,
            'id': id
        }
    })


@appfile.route('/getCode')
def getCode():
    #   0:成功 1:手机号重复 2:对同一个手机号发送短信的间隔太短

    tel = request.values.get('tel')

    privateCode = 0
    # r = None

    delTempCode()

    conn = pymysql.Connect(host=server_host, port=3306,
                           user=user, passwd=passwd, db=db, charset='utf8')
    cursor = conn.cursor()

    # 查询数据库中同一手机号是否在一定时间内有发送短信
    selectSql = "SELECT tel FROM tb_temp_code WHERE tel='%s'" % (tel)
    cursor.execute(selectSql)

    # 当有数据时,不执行发短信的操作
    if cursor.rowcount > 0:
        privateCode = 2
    else:
        # 当用户已登记的情况下不发送短信
        selectSql = "SELECT tel FROM tb_user WHERE tel='%s'" % (tel)
        cursor.execute(selectSql)

        if cursor.rowcount > 0:
            privateCode = 1
        else:
            code = random.randint(1000, 9999)
            ssender = SmsSingleSender(appid, appkey)

            try:
                result = ssender.send_with_param(
                    86, tel, template_id, [code, validTime])
                privateCode = result.result
                r = result
            except HTTPError as e:
                r = e
            except Exception as e:
                r = e

            if privateCode == 0:
                insertSql = "INSERT INTO tb_temp_code(tel, code, add_time, is_del) VALUES ('%s', '%s', %d, 0)" % (
                    tel, code, int(time.time() * 1000))

                cursor.execute(insertSql)
                conn.commit()

    cursor.close()
    conn.close()

    return json.dumps({
        'code': privateCode
    })


@appfile.route('/isLogin')
def isLogin():
    privateCode = 0
    msg = None

    token = request.values.get('token')

    conn = pymysql.Connect(host=server_host, port=3306,
                           user=user, passwd=passwd, db=db, charset='utf8')
    cursor = conn.cursor()

    selectSql = "SELECT id,name FROM tb_admin WHERE token='%s'" % (token)
    cursor.execute(selectSql)

    if cursor.rowcount == 1:
        userData = cursor.fetchone()
        msg = {
            'id': userData[0],
            'name': userData[1]
        }
    else:
        privateCode = 1

    cursor.close()
    conn.close()

    return json.dumps({
        'code': privateCode,
        'msg': msg
    })


@appfile.route('/login', methods=['POST', 'GET'])
def login():
    privateCode = 0
    msg = None

    name = request.values.get('name')
    pwd = request.values.get('pwd')

    pwd = genearteMD5(pwd)

    conn = pymysql.Connect(host=server_host, port=3306,
                           user=user, passwd=passwd, db=db, charset='utf8')
    cursor = conn.cursor()

    selectSql = "SELECT id FROM tb_admin WHERE name='%s' AND pwd='%s'" % (
        name, pwd)
    cursor.execute(selectSql)

    if cursor.rowcount == 0:
        privateCode = 1
    elif cursor.rowcount == 1:
        userData = cursor.fetchone()

        nowTime = getNowTime()

        token = genearteMD5(name + str(nowTime))

        msg = {
            'id': userData[0],
            'token': token
        }

        updateSql = "UPDATE tb_admin SET token='%s', update_time=%d WHERE id=%d" % (
            token, nowTime, userData[0])
        cursor.execute(updateSql)
        conn.commit()

    cursor.close()
    conn.close()

    return json.dumps({
        'code': privateCode,
        'msg': msg
    })


@appfile.route('/getUserList')
def getUserList():
    privateCode = 0

    start = request.values.get('start')
    count = request.values.get('count')

    conn = pymysql.Connect(host=server_host, port=3306,
                           user=user, passwd=passwd, db=db, charset='utf8')
    cursor = conn.cursor()

    selectSql = "SELECT id,name,tel,id_card,referrer,pwd,files,add_time FROM tb_user ORDER BY add_time DESC LIMIT %s,%s" % (
        start, count)
    cursor.execute(selectSql)

    results = cursor.fetchall()

    listArr = []

    for row in results:
        files = row[6]
        filesArr = []

        if files:
            for item in files.split(';'):
                item = IMAGE_PATH + item
                filesArr.append(item)

        tempItem = {
            'id': row[0],
            'name': row[1],
            'tel': row[2],
            'id_card': row[3],
            'referrer': row[4],
            'pwd': row[5],
            'files': ';'.join(filesArr),
            'add_time': row[7],
        }

        listArr.append(tempItem)

    jsonResult = json.dumps(listArr)
    jsonResult = listArr

    cursor.close()
    conn.close()

    return json.dumps({
        'code': privateCode,
        'msg': jsonResult
    })


# 删除多余的tb_temp_code表的数据
def delTempCode():
    conn = pymysql.Connect(host=server_host, port=3306,
                           user=user, passwd=passwd, db=db, charset='utf8')
    cursor = conn.cursor()

    tempTime = int(getNowTime()) - 60000 * validTime

    delSql = "DELETE FROM tb_temp_code WHERE add_time < %d" % tempTime

    cursor.execute(delSql)
    conn.commit()

    cursor.close()
    conn.close()


def genearteMD5(str):
    # 创建md5对象
    hl = hashlib.md5()

    # Tips
    # 此处必须声明encode
    # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update(str.encode(encoding='utf-8'))

    return hl.hexdigest()


def getNowTime():
    return time.time() * 1000

# 将base64编码转换为图片并保存


def base64ToPicAndSave(base64Str, picName):
    if (base64Str.index('data:') == 0):
        base64Str = base64Str.split('base64,')[1]

    imgdata = base64.b64decode(base64Str)
    with open(IMAGE_PATH + picName, 'wb') as file:
        file.write(imgdata)


@appfile.route('/save1', methods=['POST', 'GET'])
def save1():
    p1 = request.values.get("p1", type=str, default=None)

    base64ToPicAndSave(p1, 'aaa.jpg')

    return 'ok'

# test


@appfile.route('/test', methods=['get'])
def test():
    return 'url: %s , script_root: %s , path: %s , base_url: %s , url_root : %s' % (request.url, request.script_root, request.path, request.base_url, request.url_root)


if __name__ == '__main__':
    appfile.debug = True
    appfile.run(host='0.0.0.0', port=8085)
